package com.beiye.drivertransport.thematic.learning;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.frame.adapter.CommonAdapter;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.activity.TwoBaseAty;
import com.beiye.drivertransport.bean.CheckBean;
import com.beiye.drivertransport.bean.LoginUserBean;
import com.beiye.drivertransport.bean.MineUseBean;
import com.beiye.drivertransport.bean.OrgIdBean;
import com.beiye.drivertransport.bean.SpecifiedLearnAllBean;
import com.beiye.drivertransport.bean.StrationCityBean;
import com.beiye.drivertransport.bean.UpPhotoBean;
import com.beiye.drivertransport.config.AppInterfaceConfig;
import com.beiye.drivertransport.http.Login;
import com.beiye.drivertransport.utils.CameraCanUseUtils;
import com.beiye.drivertransport.utils.Constants;
import com.beiye.drivertransport.utils.FileUtil;
import com.beiye.drivertransport.utils.ImageUtil;
import com.beiye.drivertransport.utils.LogUtils;
import com.beiye.drivertransport.utils.MessageEvent;
import com.beiye.drivertransport.utils.SharePerferenceUtils;
import com.beiye.drivertransport.utils.TakePhotoDialog;
import com.beiye.drivertransport.utils.TiShiDialog;
import com.beiye.drivertransport.utils.ToastUtil;
import com.beiye.drivertransport.utils.UserManger;
import com.beiye.drivertransport.utils.Utils;
import com.githang.statusbar.StatusBarCompat;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.squareup.picasso.Picasso;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

//全部专题
public class AlltopicsActivity extends TwoBaseAty {

    ImageView img_allback;

    ListView lv_alltopics;

    View empty_view;
    ArrayList<OrgIdBean.RowsBean> orgidlist = new ArrayList<>();
    ArrayList<OrgIdBean.RowsBean> orgidsublist = new ArrayList<>();
    private SpecifiedLearnGVAdapter specifiedLearnGVAdapter;
    ArrayList<SpecifiedLearnAllBean.RowsBean> slgvlist = new ArrayList<>();

    private PopupWindow mPopWindow;
    private String idcNo;
    private String userName;

    private Bundle certListBundle;
    private String nation;
    private String address;
    private String userId;
    private String[] citys;

    //请求相机
    private static final int REQUEST_CAPTURE = 100;
    //请求相册
    private static final int REQUEST_PICK = 101;
    private File tempFile;
    //请求访问外部存储
    private static final int READ_EXTERNAL_STORAGE_REQUEST_CODE = 103;
    //请求写入外部存储
    private static final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 104;
    private String photoUrl;
    private int reapplyMark;

    private int stIdFlag;//专题标识（0：青海、四川，1：甘肃等）

    @Override
    public int getLayoutId() {
        return R.layout.activity_alltopics;
    }


    public void onClick(View view) {
        if (view.getId() == R.id.img_allback) {
            finish();
        }

    }

    @Override
    public void initData() {
        img_allback = (ImageView) findViewById(R.id.img_allback);
        lv_alltopics = (ListView) findViewById(R.id.gv_alltopics);
        empty_view = (View) findViewById(R.id.empty_view);

        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        userId = data.getUserId();

        new Login().getstrationDivision("510000", this, 5);//查询指定行政区划信息及其下级

        //注册EventBus
        EventBus.getDefault().register(this);
        StatusBarCompat.setStatusBarColor(this, Color.parseColor("#1F80C4"));

        lv_alltopics.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (Utils.isFastClicker()) {
                    return;
                }
                int stId = specifiedLearnGVAdapter.getItem(position).getStId();
                int disableMark = specifiedLearnGVAdapter.getItem(position).getDisableMark();
                String disableDesc = specifiedLearnGVAdapter.getItem(position).getDisableDesc();
                String stName = specifiedLearnGVAdapter.getItem(position).getStName();
                float price = specifiedLearnGVAdapter.getItem(position).getPrice();
                Integer uschSn = specifiedLearnGVAdapter.getItem(position).getUschSn();
                String iconUrl2 = specifiedLearnGVAdapter.getItem(position).getIconUrl2();
                Integer chargeMark = specifiedLearnGVAdapter.getItem(position).getChargeMark();
                Integer payMark = specifiedLearnGVAdapter.getItem(position).getPayMark();
                Integer tmenuMark = specifiedLearnGVAdapter.getItem(position).getTmenuMark();
                Integer qmenuMark = specifiedLearnGVAdapter.getItem(position).getQmenuMark();
                Integer peMenuMark = specifiedLearnGVAdapter.getItem(position).getPeMenuMark();
                Integer emenuMark = specifiedLearnGVAdapter.getItem(position).getEmenuMark();
                int seqTMark = specifiedLearnGVAdapter.getItem(position).getSeqTMark();
                reapplyMark=specifiedLearnGVAdapter.getItem(position).getReapplyMark();

                Integer thematicFaceRecgMark = specifiedLearnGVAdapter.getItem(position).getFaceRecgMark();
                SharePerferenceUtils.putInt(AlltopicsActivity.this, "thematicFaceRecgMark", thematicFaceRecgMark);

                SharedPreferences sp = getSharedPreferences("AlltopicsActivity", Context.MODE_PRIVATE);
                int orgMark = sp.getInt("orgMark", 0);
                int ihveMark = sp.getInt("ihveMark", 0);
                String orgName = sp.getString("orgName", "");
                String orgId = sp.getString("orgId", "");
                String adId = sp.getString("adId", "");
                String rolename = sp.getString("rolename", "");
//                if(adId.equals("500110")&&stId==100001)
//                {
//                    orgidsublist.clear();
//                    for (int i = 0;i<orgidlist.size(); i++) {
//
//                        if(orgId.equals(orgidlist.get(i).getOrgId()))
//                        {
//                            orgidsublist.add(orgidlist.get(i));
//                        }
//                    }
//                    if(orgidsublist.size()==0) {
//                        AlertDialog.Builder builder = new AlertDialog.Builder(AlltopicsActivity.this);
//                        View view1 = View.inflate(AlltopicsActivity.this, R.layout.diolog_learn_layout, null);
//                        TextView tv_message = (TextView) view1.findViewById(R.id.message);//输入内容
//                        ImageView img_erweima = (ImageView) view1.findViewById(R.id.img_erweima);//输入内容
//                        tv_message.setText("     专项培训统一通过万盛区交通运输安全服务中心入口进行学习。请在微信中搜索并关注“重庆诺信安全信息技术有限公司”，点击专项培训进行学习。");
//                        TextView btn_sure = (TextView) view1.findViewById(R.id.positiveButton);
//                        TextView btn_cancel = (TextView) view1.findViewById(R.id.negativeButton);
//                        btn_sure.setText("我知道");
//                        btn_cancel.setVisibility(View.GONE);
//                        img_erweima.setVisibility(View.VISIBLE);
//                        final AlertDialog dialog = builder.create();
//                        dialog.show();
//                        dialog.getWindow().setContentView(view1);
//                        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//                        dialog.setCancelable(true);
//                        btn_sure.setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View view) {
//                                dialog.dismiss();
//
//                            }
//                        });
//
//                        return;
//                    }
//                }else if(adId.equals("500120")&&stId==500001)
//                {
//
//                    AlertDialog.Builder builder = new AlertDialog.Builder(AlltopicsActivity.this);
//                    View view1 = View.inflate(AlltopicsActivity.this, R.layout.diolog_learn_layout, null);
//                    TextView tv_message = (TextView) view1.findViewById(R.id.message);//输入内容
//                    TextView tv_message1 = (TextView) view1.findViewById(R.id.message1);//输入内容1
//                    TextView tv_title = (TextView) view1.findViewById(R.id.title);//输入头部
//                    tv_title.setVisibility(View.VISIBLE);
//                    tv_message1.setVisibility(View.VISIBLE);
//                    tv_title.setText("温馨提示");
//                    tv_message.setText("学习继续教育请联系：");
//                    tv_message1.setText("高老师：18290298308  (微信同号)");
//                    TextView btn_sure = (TextView) view1.findViewById(R.id.positiveButton);
//                    TextView btn_cancel = (TextView) view1.findViewById(R.id.negativeButton);
//                    btn_sure.setText("取消");
//                    btn_cancel.setVisibility(View.GONE);
//                    final AlertDialog dialog = builder.create();
//                    dialog.show();
//                    dialog.getWindow().setContentView(view1);
//                    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//                    dialog.setCancelable(true);
//                    btn_sure.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View view) {
//                            dialog.dismiss();
//
//                        }
//                    });
//
//
//
//                    return;
//
//
//                }


                if (disableMark == 1)//禁用提示框
                {
                    String decstr = Utils.removeHtmlTag(disableDesc);
                    AlertDialog.Builder builder = new AlertDialog.Builder(AlltopicsActivity.this);
                    View view1 = View.inflate(AlltopicsActivity.this, R.layout.diolog_learn_layout, null);
                    TextView tv_message = (TextView) view1.findViewById(R.id.message);//输入内容
                    TextView tv_title = (TextView) view1.findViewById(R.id.title);//输入头部
                    tv_title.setVisibility(View.VISIBLE);
                    tv_title.setText("温馨提示");
                    tv_message.setText(decstr);
                    TextView btn_sure = (TextView) view1.findViewById(R.id.positiveButton);
                    TextView btn_cancel = (TextView) view1.findViewById(R.id.negativeButton);
                    btn_sure.setText("取消");
                    btn_cancel.setVisibility(View.GONE);
                    final AlertDialog dialog = builder.create();
                    dialog.show();
                    dialog.getWindow().setContentView(view1);
                    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    dialog.setCancelable(true);
                    btn_sure.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismiss();

                        }
                    });
                    return;
                }
                if (orgMark == 0) {
                    TiShiDialog.Builder builder1 = new TiShiDialog.Builder(AlltopicsActivity.this);
                    builder1.setMessage("您所在的企业" + orgName + "是无效状态，请联系管理员");
                    builder1.setTitle("提示:");
                    builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            //设置你的操作事项
                        }
                    });
                    builder1.create().show();
                    return;
                } else if (orgMark == 2) {
                    TiShiDialog.Builder builder1 = new TiShiDialog.Builder(AlltopicsActivity.this);
                    builder1.setMessage("您所在的企业" + orgName + "是待审核状态，请联系管理员");
                    builder1.setTitle("提示:");
                    builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            //设置你的操作事项
                        }
                    });
                    builder1.create().show();
                    return;
                } else if (orgMark == 3) {
                    TiShiDialog.Builder builder1 = new TiShiDialog.Builder(AlltopicsActivity.this);
                    builder1.setMessage("您所在的企业" + orgName + "是还未审核通过，请联系管理员");
                    builder1.setTitle("提示:");
                    builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            ;
                            //设置你的操作事项
                        }
                    });
                    builder1.create().show();
                    return;
                }
//                else if (orgMark == 4) {
//                    TiShiDialog.Builder builder1 = new TiShiDialog.Builder(AlltopicsActivity.this);
//                    builder1.setMessage("您" + orgName + "企业“余额”或者“学时”不足，请联系企业管理员");
//                    builder1.setTitle("提示:");
//                    builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
//                        public void onClick(DialogInterface dialog, int which) {
//                            dialog.dismiss();
//                            ;
//                            //设置你的操作事项
//                        }
//                    });
//                    builder1.create().show();
//                    return;
//                }
                SharedPreferences.Editor edit = sp.edit();
                edit.putInt("stId", stId);
                edit.putInt("tmenuMark", tmenuMark);
                edit.putInt("qmenuMark", qmenuMark);
                edit.putInt("peMenuMark", peMenuMark);
                edit.putInt("emenuMark", emenuMark);
                edit.putInt("position", position);
                edit.putString("stName", stName);
                edit.putString("iconUrl", iconUrl2);
                edit.putInt("seqTMark", seqTMark);
                edit.commit();

                Bundle bundle = new Bundle();
                bundle.putString("userName", userName);
                bundle.putString("orgId", orgId);
                bundle.putInt("stId", stId);
                bundle.putString("orgName", orgName);
                bundle.putString("adId", adId);
                bundle.putString("rolename", rolename);
                bundle.putString("iconUrl", iconUrl2);
                bundle.putInt("position", position);
                bundle.putInt("ihveMark", ihveMark);
                bundle.putInt("tmenuMark", tmenuMark);
                bundle.putInt("qmenuMark", qmenuMark);
                bundle.putInt("peMenuMark", peMenuMark);
                bundle.putInt("emenuMark", emenuMark);
                bundle.putInt("seqTMark", seqTMark);
                bundle.putInt("chargeMark", chargeMark);
                bundle.putInt("paytag",2);
                bundle.putFloat("price", price);
                bundle.putString("stName",stName);
                bundle.putInt("reapplyMark",reapplyMark);
                bundle.putString("uqcSn", null);
                certListBundle=bundle;

                if (uschSn == null) {

                    if (stId == 630011  || stId==630012) {
                        stIdFlag=0;
                        bundle.putString("province","青海");
                        certListBundle=bundle;
                        if (idcNo == null || idcNo.length() == 0) {
                            showIdcNoDialog();
                        } else {
                            bundle.putString("idcNo", idcNo);
                            //startActivity(CertListActivity.class, bundle);
                        }
                        return;
                    }

                    if (stId==730002 || stId==730003 || stId==730004 || stId==320101) {
                        stIdFlag=1;
                        if (idcNo == null || idcNo.length() == 0) {
                            showIdcNoDialog();
                            return;
                        }
                    }

                    if (stId == 510016 || stId == 510017 || stId == 510018 || stId == 510019 ) { //四川继续教育专题培训
                        if (photoUrl.equals("")) {
                            showTakePhotoPopupWindow();
                            return;
                        }
                        bundle.putString("province","四川");
                        certListBundle=bundle;
                        if (idcNo == null || idcNo.length() == 0 || nation == null || nation.length() == 0 || address == null || address.length() == 0 ) {
                            showUserMsgDialog();
                        }else{
                            bundle.putString("idcNo",idcNo);
                            //startActivity(CertListActivity.class,bundle);
                        }
                        return;
                    }

                    if (chargeMark == 1)//免费
                    {
                        LoginUserBean userInfo = UserManger.getUserInfo();
                        LoginUserBean.DataBean data = userInfo.getData();
                        String userId = data.getUserId();
                        String phoneSign = getPhoneSign();//设备的唯一标识
                        initPayMent(userId, orgId, 0, phoneSign, stId);
                    }
                    if (chargeMark == 3)//考试前付费
                    {
                        LoginUserBean userInfo = UserManger.getUserInfo();
                        LoginUserBean.DataBean data = userInfo.getData();
                        String userId = data.getUserId();
                        String phoneSign = getPhoneSign();//设备的唯一标识
                        initPayMent(userId, orgId, 0, phoneSign, stId);
                    } else if (chargeMark == 2) {//进入前付费
                        startActivity(NewPaymentActivity.class, bundle);
                    }
                } else {
                    if (chargeMark == 1) {
                        startActivity(ThematiclearningActivity.class, bundle);
                    } else if (chargeMark == 3) {
                        startActivity(ThematiclearningActivity.class, bundle);
                    } else if (chargeMark == 2) {
                        if (payMark == 2)//已付费
                        {
                            bundle.putInt("reapplyMark",reapplyMark);
                            startActivity(ThematiclearningActivity.class, bundle);
                        } else if (payMark == 0) {//待支付

                            if (stId == 630011  || stId==630012) { ;
                                bundle.putString("province","青海");
                                certListBundle=bundle;
                                if (idcNo == null || idcNo.length() == 0) {
                                    showIdcNoDialog();
                                } else {
                                    bundle.putString("idcNo", idcNo);
                                    //startActivity(CertListActivity.class, bundle);
                                }
                                return;
                            }
                            if (stId == 510016 || stId == 510017 || stId == 510018 || stId == 510019 ) { //四川继续教育专题培训

                                if (photoUrl.equals("")) {
                                    showTakePhotoPopupWindow();
                                    return;
                                }
                                bundle.putString("province","四川");
                                certListBundle=bundle;
                                if (idcNo == null || idcNo.length() == 0 || nation == null || nation.length() == 0 || address == null || address.length() == 0 ) {
                                    showUserMsgDialog();
                                }else{
                                    bundle.putString("idcNo",idcNo);
                                    //startActivity(CertListActivity.class,bundle);
                                }
                                return;
                            }
                            if(stId==730002 || stId==730003 || stId==730004 || stId==320101){//甘肃继续教育
                                stIdFlag=1;
                                certListBundle = bundle;

                                if (idcNo == null || idcNo.length() == 0) {
                                    showIdcNoDialog();
                                    return;
                                }
                            }
                            startActivity(NewPaymentActivity.class, bundle);
                        } else if (payMark == 1)//免费
                        {
                            startActivity(ThematiclearningActivity.class, bundle);
                        }
                    }

                }
            }
        });
    }

    //免费参加专项学习调购买接口
    private void initPayMent(String userId, String orgId, float price, String phoneSign, int stId) {
        new Login().getPayMentApp(userId, orgId, 2, stId, "APP", price, phoneSign, Constants.APP_ID, null, this, 2);
    }

    private void judgeData() {
        OkGo.get(AppInterfaceConfig.BASE_URL + "wx/specTWhiteOrg")
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        OrgIdBean orgIdBean = JSON.parseObject(s, OrgIdBean.class);
                        List<OrgIdBean.RowsBean> rows = orgIdBean.getRows();
                        orgidlist.clear();
                        orgidlist.addAll(rows);
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);

                    }
                });
    }

    @Override
    public void requestData() {
        Bundle bundle = getIntent().getExtras();
        String adId = bundle.getString("adId");
        String orgId = bundle.getString("orgId");
        String rolename = bundle.getString("rolename");
        String orgName = bundle.getString("orgName");
        photoUrl=bundle.getString("photoUrl");
        int orgMark = bundle.getInt("orgMark");
        int ihveMark = bundle.getInt("ihveMark");
        SharedPreferences sp = getSharedPreferences("AlltopicsActivity", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("rolename", rolename);
        edit.putString("orgId", orgId);
        edit.putString("adId", adId);
        edit.putString("orgName", orgName);
        edit.putInt("orgMark", orgMark);
        edit.putInt("ihveMark", ihveMark);
        edit.commit();
        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        String userId = data.getUserId();
        new Login().getUser(userId, this, 3);
        if (rolename.equals("我是从业人员") || rolename.equals("我是车主")) {
            new Login().getRolespecifiedlearn(adId, orgId, userId, 1 + "", "", "", this, 1);//驾驶员专项学习
        } else if (rolename.equals("我是企业负责人")) {
            new Login().getRolespecifiedlearn(adId, orgId, userId, "", 1 + "", "", this, 1);//负责人专项学习
        } else if (rolename.equals("我是企业管理人员") || rolename.equals("我是单位人员")) {
            new Login().getRolespecifiedlearn(adId, orgId, userId, "", "", 1 + "", this, 1);//安全员专项学习
        }

        judgeData();

    }

    @Override
    protected void onResume() {
        super.onResume();
        requestData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//反注册EventBus
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(MessageEvent event) {
        if (event.getType() == MessageEvent.TYPE_13) {
            SharedPreferences sp = getSharedPreferences("AlltopicsActivity", Context.MODE_PRIVATE);
            String stName = sp.getString("stName", "");
            TiShiDialog.Builder builder1 = new TiShiDialog.Builder(AlltopicsActivity.this);
            builder1.setMessage("你已成功购买 " + "[专题学习]" + stName + "。");
            builder1.setTitle("提示:");
            builder1.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    SharedPreferences sp = getSharedPreferences("AlltopicsActivity", Context.MODE_PRIVATE);
                    String orgId = sp.getString("orgId", "");
                    String orgName = sp.getString("orgName", "");
                    String rolename = sp.getString("rolename", "");
                    String iconUrl = sp.getString("iconUrl", "");
                    int stId = sp.getInt("stId", 0);
                    String adId = sp.getString("adId", "");
                    int position = sp.getInt("position", 0);
                    int ihveMark = sp.getInt("ihveMark", 0);
                    int tmenuMark = sp.getInt("tmenuMark", 0);
                    int qmenuMark = sp.getInt("qmenuMark", 0);
                    int peMenuMark = sp.getInt("peMenuMark", 0);
                    int emenuMark = sp.getInt("emenuMark", 0);
                    int seqTMark = sp.getInt("seqTMark", 0);
                    Bundle bundle = new Bundle();
                    bundle.putString("orgId", orgId);
                    bundle.putString("rolename", rolename);
                    bundle.putInt("stId", stId);
                    bundle.putString("orgName", orgName);
                    bundle.putString("iconUrl", iconUrl);
                    bundle.putString("adId", adId);
                    bundle.putInt("position", position);
                    bundle.putInt("ihveMark", ihveMark);
                    bundle.putInt("tmenuMark", tmenuMark);
                    bundle.putInt("qmenuMark", qmenuMark);
                    bundle.putInt("peMenuMark", peMenuMark);
                    bundle.putInt("emenuMark", emenuMark);
                    bundle.putInt("seqTMark", seqTMark);
                    bundle.putInt("reapplyMark",reapplyMark);
                    startActivity(ThematiclearningActivity.class, bundle);
                }
            });

            builder1.create().show();

        } else if (event.getType() == MessageEvent.TYPE_2) {
            TiShiDialog.Builder builder1 = new TiShiDialog.Builder(AlltopicsActivity.this);
            builder1.setMessage("你购买失败");
            builder1.setTitle("提示:");
            builder1.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    ;
                }
            });

            builder1.create().show();
        }
    }

    @Override
    public void onSuccess(String result, Call call, Response response, int what) {
        super.onSuccess(result, call, response, what);
        if (what == 1) {
            SpecifiedLearnAllBean specifiedLearnAllBean = JSON.parseObject(result, SpecifiedLearnAllBean.class);
            List<SpecifiedLearnAllBean.RowsBean> rows = specifiedLearnAllBean.getRows();
            slgvlist.clear();
            if (rows.size() == 0) {
                lv_alltopics.setEmptyView(empty_view);
                return;
            }
            for (int i = 0; i < rows.size(); i++) {
                if (rows.get(i).getShowTrml() != 3) {
                    slgvlist.add(rows.get(i));
                }
            }
            specifiedLearnGVAdapter = new SpecifiedLearnGVAdapter(AlltopicsActivity.this, slgvlist, R.layout.alltopics_item_layout);
            lv_alltopics.setAdapter(specifiedLearnGVAdapter);
        } else if (what == 2) {
            SharedPreferences sp = getSharedPreferences("AlltopicsActivity", Context.MODE_PRIVATE);
            String orgId = sp.getString("orgId", "");
            String orgName = sp.getString("orgName", "");
            String rolename = sp.getString("rolename", "");
            String iconUrl = sp.getString("iconUrl", "");
            int stId = sp.getInt("stId", 0);
            String adId = sp.getString("adId", "");
            int position = sp.getInt("position", 0);
            int ihveMark = sp.getInt("ihveMark", 0);
            int tmenuMark = sp.getInt("tmenuMark", 0);
            int qmenuMark = sp.getInt("qmenuMark", 0);
            int peMenuMark = sp.getInt("peMenuMark", 0);
            int emenuMark = sp.getInt("emenuMark", 0);
            int seqTMark = sp.getInt("seqTMark", 0);
            Bundle bundle = new Bundle();
            bundle.putString("orgId", orgId);
            bundle.putString("rolename", rolename);
            bundle.putInt("stId", stId);
            bundle.putString("orgName", orgName);
            bundle.putString("adId", adId);
            bundle.putString("iconUrl", iconUrl);
            bundle.putInt("position", position);
            bundle.putInt("ihveMark", ihveMark);
            bundle.putInt("tmenuMark", tmenuMark);
            bundle.putInt("qmenuMark", qmenuMark);
            bundle.putInt("peMenuMark", peMenuMark);
            bundle.putInt("emenuMark", emenuMark);
            bundle.putInt("seqTMark", seqTMark);
            bundle.putInt("reapplyMark",reapplyMark);
            startActivity(ThematiclearningActivity.class, bundle);
        }else if(what==3){
            MineUseBean mineUseBean = JSON.parseObject(result, MineUseBean.class);
            MineUseBean.DataBean data = mineUseBean.getData();
            idcNo = data.getIdcNo();
            nation=data.getNation();
            address=data.getAddress();
            userName = data.getUserName();
        }else if(what == 4){
            if(stIdFlag==0){
                //startActivity(CertListActivity.class, certListBundle);
            }else if(stIdFlag==1){
                startActivity(ThematiclearningActivity.class, certListBundle);
            }
        }else if(what == 5){
            StrationCityBean strationCityBean = JSON.parseObject(result, StrationCityBean.class);
            StrationCityBean.DataBean data = strationCityBean.getData();
            List<StrationCityBean.DataBean.NextListBean> nextList = data.getNextList();
            citys=new String[nextList.size()+1];
            citys[0]="选择市";
            for(int i=0;i<nextList.size();i++){
                citys[i+1]=nextList.get(i).getNextAdName();
            }
        }
    }

    @Override
    public void onError(String result, Call call, Response response, int what) {
        if (what == 2) {
            CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
            //     int code = checkBean.getCode();
            String msg = checkBean.getMsg();
            TiShiDialog.Builder builder1 = new TiShiDialog.Builder(AlltopicsActivity.this);
            builder1.setMessage(msg);
            builder1.setTitle("提示:");
            builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder1.create().show();
        }
        super.onError(result, call, response, what);
    }

    public class SpecifiedLearnGVAdapter extends CommonAdapter<SpecifiedLearnAllBean.RowsBean> {
        private final List<SpecifiedLearnAllBean.RowsBean> mList;
        private Context context;
        // 标记用户当前选择
        private int index = -1;

        public SpecifiedLearnGVAdapter(Context context, List<SpecifiedLearnAllBean.RowsBean> mList, int itemLayoutId) {
            super(context, mList, itemLayoutId);
            this.context = context;
            this.mList = mList;

        }

        @Override
        public void convert(com.android.frame.adapter.ViewHolder holder, SpecifiedLearnAllBean.RowsBean item, final int position) {


            ImageView img_alltop = holder.getView(R.id.img_alltop);
            TextView tv_name = holder.getView(R.id.tv_name);
            TextView tv_inside = holder.getView(R.id.tv_inside);
            String iconUrl = mList.get(position).getIconUrl();
            SharedPreferences sp = getSharedPreferences("AlltopicsActivity", Context.MODE_PRIVATE);
            String rolename = sp.getString("rolename", "");

            if (rolename.equals("我是从业人员")) {
                tv_name.setText("驾驶员");
            } else if (rolename.equals("我是企业负责人")) {
                tv_name.setText("负责人");
            } else if (rolename.equals("我是企业管理人员") || rolename.equals("我是单位人员")) {
                tv_name.setText("安全员");
            } else if (rolename.equals("我是车主")) {
                tv_name.setText("车主");
            }
            if (iconUrl != null) {
                Picasso.with(mContext).load(Uri.parse(iconUrl)).placeholder(R.mipmap.no_data2).into(img_alltop);
            }
            Integer uschSn = mList.get(position).getUschSn();
            // double price = mList.get(position).getPrice();
            Integer chargeMark = mList.get(position).getChargeMark();
            Integer payMark = mList.get(position).getPayMark();
            if (uschSn == null) {
                if (chargeMark == 1) {
                    tv_inside.setText("进入");
                    tv_inside.setTextColor(getResources().getColor(R.color.project_blue));
                } else if (chargeMark == 2 || chargeMark == 3) {
                    tv_inside.setText("未参加");
                    tv_inside.setTextColor(getResources().getColor(R.color.project_redsecond));
                }
            } else {
                if (chargeMark == 1) {
                    tv_inside.setText("进入");
                    tv_inside.setTextColor(getResources().getColor(R.color.project_blue));
                } else if (chargeMark == 3) {
                    tv_inside.setText("进入");
                    tv_inside.setTextColor(getResources().getColor(R.color.project_blue));
                } else if (chargeMark == 2) {
                    if (payMark == 2) {
                        tv_inside.setText("进入");
                        tv_inside.setTextColor(getResources().getColor(R.color.project_blue));
                    } else {
                        tv_inside.setText("进入");
                        tv_inside.setTextColor(getResources().getColor(R.color.project_blue));
                    }

                }
            }
        }


    }

    //获取手机的唯一标识
    @SuppressLint("MissingPermission")
    public String getPhoneSign() {
        StringBuilder deviceId = new StringBuilder();
        // 渠道标志
        deviceId.append("a");
        try {
            // IMEI（imei）
            TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            String imei = tm.getDeviceId();
            if (!TextUtils.isEmpty(imei)) {
                deviceId.append("imei");
                deviceId.append(imei);
                return deviceId.toString();
            }
            //序列号（sn）
            String sn = tm.getSimSerialNumber();
            if (!TextUtils.isEmpty(sn)) {
                deviceId.append("sn");
                deviceId.append(sn);
                return deviceId.toString();
            }
            //如果上面都没有， 则生成一个id：随机码
            String uuid = getUUID();
            if (!TextUtils.isEmpty(uuid)) {
                deviceId.append("id");
                deviceId.append(uuid);
                return deviceId.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            deviceId.append("id").append(getUUID());
        }
        return deviceId.toString();
    }

    /**
     * 得到全局唯一UUID
     */
    private String uuid;

    public String getUUID() {
        SharedPreferences mShare = getSharedPreferences("uuid", MODE_PRIVATE);
        if (mShare != null) {
            uuid = mShare.getString("uuid", "");
        }
        if (TextUtils.isEmpty(uuid)) {
            uuid = UUID.randomUUID().toString();
            mShare.edit().putString("uuid", uuid).commit();
        }
        return uuid;
    }

    private void showUserMsgDialog() {
        //设置contentView
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_moreinput_layout, null);
        mPopWindow = new PopupWindow(contentView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
        //设置各个控件的点击响应
        mPopWindow.showAtLocation(contentView, Gravity.CENTER, 0, 0);

        EditText etIdcNo = (EditText) contentView.findViewById(R.id.dg_moreInput_et_idcNo);//输入内容
        EditText etNation = (EditText) contentView.findViewById(R.id.dg_moreInput_et_nation);//输入内容
        EditText etAddress = (EditText) contentView.findViewById(R.id.dg_moreInput_et_address);//输入内容
        TextView btn_sure = (TextView) contentView.findViewById(R.id.positiveButton);
        TextView btn_false = (TextView) contentView.findViewById(R.id.negativeButton);
        Spinner spCity = (Spinner) contentView.findViewById(R.id.dg_moreInput_rv_city);

        if(!(idcNo==null || idcNo.length()==0)){
            etIdcNo.setText(idcNo);
        }

        if(!(nation==null || nation.length()==0)){
            etNation.setText(nation);
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(AlltopicsActivity.this, android.R.layout.simple_spinner_item , citys);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spCity.setAdapter(adapter);
        spCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                address=citys[i];
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });



        btn_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String idcNoStr = etIdcNo.getText().toString().trim();
                String nationStr=etNation.getText().toString().trim();
                String city=etAddress.getText().toString().trim();


                if(idcNoStr.length()==0){
                    showToast("请填写身份证号码");
                    return;
                }
                if(!IsIDcard(idcNoStr)){
                    showToast("身份证无效");
                    return;
                }

                if(nationStr.length()==0){
                    showToast("请填写民族");
                    return;
                }

                if(address.equals("选择市")){
                    showToast("请选择所在城市");
                    return;
                }

                if(city.length()==0){
                    showToast("请填写详细地址");
                    return;
                }

                idcNo=idcNoStr;
                nation=nationStr;
                address="四川省"+address+city;
                certListBundle.putString("idcNo",idcNo);
                new Login().userAccountUpdateAddNation(userId,idcNo,nation,address, AlltopicsActivity.this,4);

                mPopWindow.dismiss();
            }
        });

        btn_false.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopWindow.dismiss();
            }
        });

    }

    private void showIdcNoDialog() {
        //设置contentView
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_input_layout, null);
        mPopWindow = new PopupWindow(contentView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
        //设置各个控件的点击响应
        mPopWindow.showAtLocation(contentView, Gravity.CENTER, 0, 0);



        EditText tv_message = (EditText) contentView.findViewById(R.id.message);//输入内容
        TextView btn_sure = (TextView) contentView.findViewById(R.id.positiveButton);


        btn_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                idcNo = tv_message.getText().toString().trim();
                if(idcNo.length()==0){
                    showToast("请填写身份证号码");
                    return;
                }
                if(!IsIDcard(idcNo)){
                    showToast("身份证无效");
                    return;
                }
                certListBundle.putString("idcNo",idcNo);
                new Login().getImputUserID(userId, idcNo,AlltopicsActivity.this,4);
                mPopWindow.dismiss();
            }
        });
        contentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopWindow.dismiss();
            }
        });
    }

    public boolean IsIDcard(String str) {
        String regex = "(^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{2}[0-9Xx]$)";
        return match(regex, str);
    }
    private boolean match(String regex, String str) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        return matcher.matches();
    }

    private void showTakePhotoPopupWindow() {
        TakePhotoDialog.Builder builder = new TakePhotoDialog.Builder(AlltopicsActivity.this);
        builder.setTitle("为方便后台管理员审核您的日常培训");
        builder.setMessage("请上传您的个人照片");
        builder.setPositiveButton("从手机中选择照片", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                //权限判断
                if (ContextCompat.checkSelfPermission(AlltopicsActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请READ_EXTERNAL_STORAGE权限
                    ActivityCompat.requestPermissions(AlltopicsActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                            READ_EXTERNAL_STORAGE_REQUEST_CODE);
                } else {
                    //跳转到相册
                    gotoPhoto();
                }

                dialog.dismiss();

                //设置您的操作事项
            }
        });
        builder.setPositiveButton1("拍摄照片", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                //权限判断
                if (ContextCompat.checkSelfPermission(AlltopicsActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请WRITE_EXTERNAL_STORAGE权限
                    ActivityCompat.requestPermissions(AlltopicsActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
                } else {
                    //跳转到调用系统相机

                    if (!CameraCanUseUtils.isCameraCanUse()) {
                        ToastUtil.showShortToast(AlltopicsActivity.this, "请到手机设置界面里找驾运宝允许开启照相");
                        return;
                    }

                    gotoCamera();
                }
                dialog.dismiss();

                //设置您的操作事项
            }
        });
        builder.setNegativeButton("跳过", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                //设置您的操作事项
            }
        });
        builder.create().show();


    }


    //打开相册
    private void gotoPhoto() {
        Log.d("evan", "*****************打开图库********************");
        //跳转到调用系统图库
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(Intent.createChooser(intent, "请选择图片"), REQUEST_PICK);
    }

    //打开相机
    private void gotoCamera() {
        Log.d("evan", "*****************打开相机********************");
        //创建拍照存储的图片文件
        tempFile = new File(FileUtil.checkDirPath(Environment.getExternalStorageDirectory().getPath() + "/image/"), System.currentTimeMillis() + ".jpg");

        //跳转到调用系统相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //设置7.0中共享文件，分享路径定义在xml/file_paths.xml
            intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(AlltopicsActivity.this, com.beiye.drivertransport.BuildConfig.APPLICATION_ID + ".fileProvider", tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
        }
        startActivityForResult(intent, REQUEST_CAPTURE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        switch (requestCode) {
            case REQUEST_CAPTURE: //调用系统相机返回
                if (resultCode == Activity.RESULT_OK) {
                    Uri uri = Uri.fromFile(tempFile);
                    String cropImagePath = FileUtil.getRealFilePathFromUri(AlltopicsActivity.this, uri);
                    File file = new File(cropImagePath);
                    LoginUserBean userInfo = UserManger.getUserInfo();
                    LoginUserBean.DataBean data = userInfo.getData();
                    String userId = data.getUserId();
                    try {
                        FileInputStream fis = new FileInputStream(file);
                        Bitmap bitmapByUrl = BitmapFactory.decodeStream(fis);
                        bitmapByUrl = ImageUtil.compressScale(bitmapByUrl);
                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                        bitmapByUrl.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                        bos.flush();
                        bos.close();
                        uploadImg(file, userId);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {

                    }
                }
                break;
            case REQUEST_PICK:  //调用系统相册返回
                if (resultCode == Activity.RESULT_OK) {
                    Uri uri = intent.getData();
                    String cropImagePath = FileUtil.getRealFilePathFromUri(AlltopicsActivity.this, uri);
                    File file = new File(cropImagePath);
                    LoginUserBean userInfo = UserManger.getUserInfo();
                    LoginUserBean.DataBean data = userInfo.getData();
                    String userId = data.getUserId();
                    try {
                        FileInputStream fis = new FileInputStream(file);
                        Bitmap bitmapByUrl = BitmapFactory.decodeStream(fis);
                        bitmapByUrl = ImageUtil.compressScale(bitmapByUrl);
                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                        bitmapByUrl.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                        bos.flush();
                        bos.close();
                        uploadImg(file, userId);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {

                    }
                }
                break;
        }
    }

    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    private final OkHttpClient client = new OkHttpClient();

    private void uploadImg(File mediaFile, String userId) {
        // mImgUrls为存放图片的url集合
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

        if (mediaFile != null) {
            builder.addFormDataPart("headPhoto", mediaFile.getName(), RequestBody.create(MEDIA_TYPE_PNG, mediaFile));
            builder.addFormDataPart("userId", userId);
        }
        MultipartBody requestBody = builder.build();
        //构建请求
        Request request = new Request.Builder()
                .url(AppInterfaceConfig.BASE_URL + "wx/uploadOfHeadPhoto")//地址
                .post(requestBody)//添加请求体
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                LogUtils.e("上传失败", e.getLocalizedMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                LogUtils.e("上传成功", str);
                UpPhotoBean upPhotoBean = JSON.parseObject(str, UpPhotoBean.class);
                String data = upPhotoBean.getData();
                Looper.prepare();
                usefacephoto(); //人脸识别要求上传头像和签名
                Looper.loop();
                LogUtils.e("上传图片", data);

            }
        });

    }

    private void usefacephoto() {
        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        if (data == null) {
            return;
        }
        String userId = data.getUserId();
        new Login().getUser(userId, this, 12);
    }
}
